package q67_addBinary;

public class Solution_1 {
    /*
    按位运算 类似于第二题链表的两数之和
     */
    public String addBinary(String a, String b) {
        int l1 = a.length() - 1, l2 = b.length() - 1;
        char carry = '0';

        StringBuilder sb = new StringBuilder();
        while (l1 >= 0 || l2 >= 0) {
            char c1 = l1 >= 0 ? a.charAt(l1) : '0';
            char c2 = l2 >= 0 ? b.charAt(l2) : '0';
            if (c1 == '0' && c2 == '0') {
                sb.insert(0, carry);
                carry = '0';
            }else if (c1 == '1' && c2 == '1') {
                sb.insert(0, carry);
                carry = '1';
            }else if (carry == '0') {
                sb.insert(0, '1');
            }else {
                sb.insert(0, '0');
            }
            l1--;
            l2--;
        }
        if (carry == '1') {
            sb.insert(0, carry);
        }

        return sb.toString();
    }
}
